package com.example.detectivedemo.application;

import com.example.detectivedemo.domain.player.Player;
import com.example.detectivedemo.domain.player.PlayerService;
import com.example.detectivedemo.infrastructure.player.LocalPlayerRepository;
import ohos.data.DatabaseHelper;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Optional;

/**
 * 玩家应用服务类
 * 作为领域层和表示层之间的桥梁，提供应用级别的玩家服务
 */
public class PlayerAppService {
    
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00202, "PlayerAppService");
    
    private static PlayerAppService instance;
    private final PlayerService playerService;
    
    // 单例模式
    private PlayerAppService(DatabaseHelper databaseHelper) {
        // 初始化基础设施层
        LocalPlayerRepository playerRepository = new LocalPlayerRepository(databaseHelper);
        
        // 初始化领域服务层
        this.playerService = new PlayerService(playerRepository);
        
        HiLog.i(LABEL, "PlayerAppService initialized");
    }
    
    // 获取单例实例
    public static synchronized PlayerAppService getInstance(DatabaseHelper databaseHelper) {
        if (instance == null) {
            instance = new PlayerAppService(databaseHelper);
        }
        return instance;
    }
    
    // 注册新玩家
    public Player registerPlayer(String username, String nickname) {
        try {
            return playerService.register(username, nickname);
        } catch (IllegalArgumentException e) {
            HiLog.e(LABEL, "Register player failed: %{public}s", e.getMessage());
            throw e;
        }
    }
    
    // 玩家登录
    public Player loginPlayer(String username) {
        try {
            return playerService.login(username);
        } catch (IllegalArgumentException e) {
            HiLog.e(LABEL, "Login player failed: %{public}s", e.getMessage());
            throw e;
        }
    }
    
    // 玩家退出登录
    public boolean logoutPlayer(String playerId) {
        return playerService.logout(playerId);
    }
    
    // 获取玩家信息
    public Optional<Player> getPlayerInfo(String playerId) {
        return playerService.getPlayerInfo(playerId);
    }
    
    // 更新玩家昵称
    public Player updatePlayerNickname(String playerId, String newNickname) {
        try {
            return playerService.updateNickname(playerId, newNickname);
        } catch (IllegalArgumentException e) {
            HiLog.e(LABEL, "Update player nickname failed: %{public}s", e.getMessage());
            throw e;
        }
    }
    
    // 玩家完成案件
    public Player completeCase(String playerId, int caseScore) {
        try {
            return playerService.completeCase(playerId, caseScore);
        } catch (IllegalArgumentException e) {
            HiLog.e(LABEL, "Complete case failed: %{public}s", e.getMessage());
            throw e;
        }
    }
    
    // 加载玩家状态
    public Optional<Player> loadPlayerState(String playerId) {
        return playerService.loadPlayerState(playerId);
    }
}